package com.jayson.server.catalina;

import com.jayson.server.utils.HttpProtocolUtil;
import com.jayson.server.utils.StaticResourceUtil;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;

public class Response {

    private OutputStream outputStream;

    public Response(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public OutputStream getOutputStream() {
        return outputStream;
    }

    public void setOutputStream(OutputStream outputStream) {
        this.outputStream = outputStream;
    }

    public void outWrite(String content) throws IOException {
        this.outputStream.write(content.getBytes());
    }

    public void outWrite200(String content) throws IOException {
        outWrite(HttpProtocolUtil.getHttpHeader200(content.getBytes().length) + content);
    }

    public void outputHtml(String path) throws IOException {
        String absolutePath = StaticResourceUtil.getAbsolutePath(path);
        File file = new File(absolutePath);
        if(file.exists() && file.isFile()){
            StaticResourceUtil.outputStaticResource(new FileInputStream(file), this.outputStream);
        } else {
            outWrite(HttpProtocolUtil.getHttpHeader404());
        }
    }
}
